define(['moment'], function () {
    return ['$scope', '$rootScope', '$filter', '$stateParams', '$mdDialog', 'config', 'MMWService', '$calculater',
        function ($scope, $rootScope, $filter, $stateParams, $mdDialog, config, $MMWService, $calculater) {

            $scope.init = function () {
                $MMWService.PNIGList = {};
                $scope.warehouseInfo = {
                    type: '', product_warehouse: '', storage: '',
                    plot_info_detail: [],
                    mono: '', productno: '', plot_no: '', erp_doc_type: '', labelno: ''
                };

                $scope.type = '0';
                $scope.selectedList = [];
                //$scope.printdata = []
                $scope.selectedPrintList = [];
                $scope.printList = [];
                $scope.warehouseInfo.productno = '';               
                $scope.warehouseInfo.mono = '';
                $scope.warehouseInfo.select_type = 3;
                $scope.do_flag = 0;
                $scope.changeNumOrNot = 0;
                $scope.Copies = '1';
               
            };

            $scope.back = function () {
                $scope.$root.hideMenu();
                $scope.$root.changeProgram('home', true);
            };

            //查询服务
            $scope.search = function () {
                var content = {
                    productno: $scope.warehouseInfo.productno,
                    mono: $scope.warehouseInfo.mono
                };
                warehousePlotInfoGet(content, function (response) {                                  
                    if ($scope.do_flag == 0) {
                        $scope.warehouseInfo.plot_info_detail = response.mono_detail;
                    } else {
                        $scope.warehouseInfo.plot_info_detail = response.materialno_detail;
                    }

                    //if (response && response.mono_detail.length > 0) {
                    //    //response.forEach(function(item){
                    //    //    $scope.selectedList.forEach(function(select_item){
                    //    //        if(item.wo_no === select_item.wo_no && item.plot_no === select_item.plot_no && item.item_name === select_item.item_name){
                    //    //            item.qty = (+select_item.qty);
                    //    //            item.storage_qty = (+select_item.storage_qty)
                    //    //            item.disconnect = true;
                    //    //            if(!item.qty){//如果item.qty減完是零，則刪除此列
                    //    //                response.splice(response.indexOf(item),1)
                    //    //            }
                    //    //        }
                    //    //    });
                    //    //});
                                         
                });
            };
            //工单余料
            $scope.ClickDoFlag = function(){
                //if($scope.selectedList.length>0){
                //    $scope.$root.showAlert($filter('translate')('B1203.msg.already_selected'));
                //} else {
                //    $scope.warehouseInfo.plot_info_detail = [];
                //    $scope.selectedList = [];
                //    if($scope.do_flag == 1){
                //        $scope.do_flag = 0;
                       
                //    } else {
                //        $scope.do_flag = 1;                       
                //    }
                //}
            };

            //取得產品編號
            $scope.loadProductNo = function () {
                var page_mode;
                //20170704 modify by Dustdusk for 入庫產品清單查詢優化
                if($scope.type == '0'){
                    page_mode = 18;
                } else if($scope.type == '1'){
                    page_mode = 19;
                }
                $MMWService.showQueryListPNIG({
                    page_mode: page_mode,
                    pageRecord:50,
                    key:'page_no',
                    condition: [
                        { name: $filter('translate')('common.queryList.item_c'), column_name: 'B.ProductNo', query_mode: '2', value: $scope.warehouseInfo.productno || '' },
                        {name:$filter('translate')('common.queryList.item_n'), column_name:'B.ProductName', query_mode:'2', value:''}
                    ],
                    header: [
                        {label:$filter('translate')('common.queryList.item_c'), code:'page_no'},
                        {label:$filter('translate')('common.queryList.item_n'), code:'page_name'}
                    ],
                    selectCode: $scope.warehouseInfo.productno,
                    confirm : function(selectItem){
                        $scope.warehouseInfo.productno = selectItem.page_no;
                        //$scope.warehouseInfo.item_name = selectItem.page_name;
                        $scope.warehouseInfo.mono = '';
                    }
                });
            };

            //取得工單編號
            $scope.loadMoNO = function () {
                var page_mode;               
                if($scope.type == '0'){
                    page_mode = 20;
                } else if($scope.type == '1'){
                    page_mode = 21;
                }
                $MMWService.showQueryListPNIG({
                    page_mode: page_mode,
                    pageRecord:50,
                    condition: [
                        { name: $filter('translate')('common.queryList.wo_c'), column_name: 'C.MoNo', query_mode: '2', value: $scope.warehouseInfo.mono}
                    ],
                    header: [
                        {label:$filter('translate')('common.queryList.wo_c'), code:'page_no'}
                    ],
                    setCondition:function(conditions){
                        if ($scope.warehouseInfo.productno && $scope.warehouseInfo.productno != '')
                            conditions.push({ column_name: 'B.ProductNo', query_mode: '0', value: $scope.warehouseInfo.productno, merge_condition_model: 'AND' });

                        return conditions;
                    },
                    selectCode: $scope.warehouseInfo.mono,
                    confirm : function(selectItem){
                        $scope.warehouseInfo.mono = selectItem.page_no;
                    }
                });
            };
            //標籤編號開窗
            $scope.BarcodeSelect = function () {

                var page_mode;
                page_mode = 'labelno_detail';
                $MMWService.showQueryListPNIG({
                    page_mode: page_mode,
                    pageRecord: 50,
                    key: 'page_no',
                    condition: [
                        { name: $filter('translate')('B1203_SearchLaberNo.laber_no_list'), column_name: 'A.LabelNO', query_mode: '2', value: $scope.warehouseInfo.labelno || '' },
                    ],
                    header: [
                        { label: $filter('translate')('B1203_SearchLaberNo.laber_no_list'), code: 'page_no' },
                        { label: $filter('translate')('B1203_SearchLaberNo.description_list'), code: 'description' },
                        { label: $filter('translate')('B1203_SearchLaberNo.formatfile_type_list'), code: 'formatfiletype' },
                        { label: $filter('translate')('B1203_SearchLaberNo.formatfilename_type_list'), code: 'formatfilename' }
                    ],
                    selectCode: $scope.warehouseInfo.labelno,
                    confirm: function (selectItem) {
                        $scope.warehouseInfo.labelno = selectItem.page_no;
                                              
                    }
                });


                //$mdDialog.dialog(
                //    'module/moduleB/program/B12/B1203/B1203_SearchLaberNo.tmp.html',
                //   SearchLaberNoController

                //);

            };


            //选择按钮
            $scope.pickTarget = function () {
                var targetArray = [];
                for (var i = 0; i < $scope.warehouseInfo.plot_info_detail.length; i++) {
                    if ($scope.warehouseInfo.plot_info_detail[i].mono.indexOf($scope.warehouseInfo.mo_no) != -1) {
                        var target = $scope.warehouseInfo.plot_info_detail[i];
                        let repeatStorage = check_select_list_repeat(target);
                         target.checked = true;
                         target.storage_qty = target.qty;
                         target.qty = target.qty;
                         check_select_list(target,repeatStorage);                         
                         targetArray.push(target);     
                    }
                }
                for (var i = 0; i < targetArray.length; i++) {
                    $scope.warehouseInfo.plot_info_detail.splice($scope.warehouseInfo.plot_info_detail.indexOf(targetArray[i]), 1);
                }
              
            };
           
            function check_select_list(click_data,key){//如果已選清單有該則入庫項目，清掉原項目並新增該項目
                //if(typeof(key) == 'number' && key!==-1){
                //    $scope.selectedList.splice(key,1);
                //}
                $scope.selectedList.unshift(angular.copy(click_data)); // 20200914 modify by WeiTing for M#78029 - 修改下方聯產品時不可同步異動到上方未選擇的資料。
            }

            function check_select_list_repeat(data){
                let repeatStorage = -1;
                $scope.selectedList.forEach(function(item,key){
                    if (item.mono === data.mono && item.productno === data.productno ) {
                         //有重複輸入
                         repeatStorage = key; 
                    }    
                });
                return repeatStorage;
            }
            //加号（+）图标按钮
            $scope.itemCheck = function (index, data) {

                let repeatStorage = check_select_list_repeat(data);//檢查selectList內有無同一筆資料                   
                data.qty = data.qty;;
                check_select_list(data, repeatStorage);
                var _index = $scope.warehouseInfo.plot_info_detail.indexOf(data);
                $scope.warehouseInfo.plot_info_detail.splice(_index, 1);

            };
            //减号图标按钮
            $scope.returnTarget = function (index, data) {
                var searchrepeat = false;
                for (var i = 0 ; i < $scope.warehouseInfo.plot_info_detail.length ; i++) {
                    if ($scope.type == 0) {
                        if ($scope.warehouseInfo.plot_info_detail[i].plot_no == data.plot_no && $scope.warehouseInfo.plot_info_detail[i].qty == data.qty) {
                            searchrepeat = true;
                            break;
                        }
                    } else if ($scope.type == 1) {
                        if ($scope.warehouseInfo.plot_info_detail[i].lot_serial == data.lot_serial && $scope.warehouseInfo.plot_info_detail[i].error_no == data.error_no) {
                            searchrepeat = false;
                            break;
                        }
                    }
                }

                data.checked = !data.checked;
                data.qty = data.qty
              
                if ($scope.type == 0 && data.joint_trigger == 'Y') {
                    data.item_no = data.old_item_no || data.item_no;
                    data.item_name = data.old_item_name || data.item_name;
                    data.item_unit_no = data.old_item_unit_no || data.item_unit_no;
                    data.item_ver = data.old_item_ver || data.item_ver;
                    delete data.joint_trigger;
                }

                $scope.selectedList.splice(index, 1);
                $scope.warehouseInfo.plot_info_detail.splice(data.warehouse_index, 0, data);//把data放回warehouse陣列
 
            };

            //开窗工单
            $scope.openStoragePlot = function (data, repeatStorage, index) {
                $mdDialog.dialog(
                    'module/moduleB/program/B12/B1203/B1203_StoragePlot.tmp.html',
                    function (dialog) {
                        dialog.storage_qty = data.qty;                       
                        dialog.materiallotno = '';
                        return {
                            storage_qty:dialog.storage_qty,
                            storage_plot: data.materialno,
                            materiallotno: data.materiallotno,
                            changeNumOrNot:$scope.do_flag,                           
                            qty:data.qty,
                            back: function () {
                                dialog.hide();
                            },
                            clearPlot: function () {
                                dialog.storage_plot = '';
                            },
                            //20200421 modify by Oliver for M#70010 標準功能開發_ 分量入庫
                            confirm: function () {
                                var _index = $scope.warehouseInfo.plot_info_detail.indexOf(data);
                                if(dialog.repeatStorage == -1){//沒有重複輸入
                                    data.storage_qty=dialog.storage_qty;//更新入庫數量
                                    if (dialog.materialno != '') {
                                        data.storage_plot = dialog.storage_plot;
                                        data.checked = !data.checked;
                                        if(Number(dialog.qty) - Number(dialog.storage_qty) >= 0){//如果入庫數量等於
                                            data.qty = (+dialog.qty) - (+dialog.storage_qty);
                                            data.warehouse_index=_index;
                                            check_select_list(data,dialog.repeatStorage);
                                            // $scope.selectedList.push(data);
                                            if(Number(dialog.qty) -Number(dialog.storage_qty) == 0){
                                                $scope.warehouseInfo.plot_info_detail.splice(_index, 1); 
                                            }
                                            dialog.hide();  
                                        }else{
                                            showAlert($filter('translate')('B1203_StoragePlot.msg.storage_qty_exceed_qty'));
                                            return;
                                        }    
                                    } else {
                                        // 如果輸入空值，則帶入原本的生產批號。
                                        data.storage_plot = data.materialno;
                                        data.checked = !data.checked;
                                        check_select_list(data,dialog.repeatStorage);
                                        // $scope.selectedList.push(data);
                                        $scope.warehouseInfo.plot_info_detail.splice(_index, 1);
                                        dialog.hide();     
                                    };
                                }else{
                                    /*如有bug優先檢查此處，當selectlist有值時的檢查*/ 
                                    if((+dialog.qty) - (+dialog.storage_qty) >= 0){
                                        data.qty=Number(dialog.qty) - Number(dialog.storage_qty);
                                        data.storage_qty = (+data.storage_qty) + (+dialog.storage_qty);
                                        data.storage_plot = data.materialno;
                                        data.materiallotno = dialog.materiallotno;
                                        check_select_list(data,dialog.repeatStorage);
                                        var _index = $scope.warehouseInfo.plot_info_detail.indexOf(data);
                                        if(data.qty == 0){
                                            $scope.warehouseInfo.plot_info_detail.splice(_index, 1); 
                                        }
                                        dialog.hide();
                                    }else{
                                        showAlert($filter('translate')('B1203_StoragePlot.msg.storage_qty_exceed_qty'));
                                    }
                                }
                            } 
                        }
                    }
                );
            };

            //取得明细資料            
            function warehousePlotInfoGet(content, feedback) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.get_tbloemomaterialstate_detail',
                    content: content,
                    success: function (data) {
                        feedback(data);
                    },
                    error: function(res) {
                        $scope.warehouseInfo.plot_info_detail = []
                        $scope.$root.showAlert(res.Message)
                    }
                });
            }
            
           

            //function SearchLaberNoController(dialog) {
                

            //    var controller = {                   
            //        labernoInfo: [],
            //        //查询
            //        search: function () {
            //            $MMWService.sendToServer({
            //                uri: 'ServicesSTD.Module_SN.get_tblprdlabelbasis_detail',
            //                content: {labelno:dialog.labernoInfo.labelno},
            //                success: function (data, response) {
            //                    dialog.labernoInfo.detail = data.labelno_detail;
            //                }
            //            });
            //        },
                                                          
            //        close: function () {

            //            dialog.hide();
            //        },

            //        confirm: function () {
            //            var count = 0;
            //            for (var i = 0 ; i < dialog.labernoInfo.detail.length ; i++) {                           
            //                if (dialog.labernoInfo.detail[i].btn_mode == true) {                               
            //                    $scope.selectedPrintList.push(dialog.labernoInfo.detail[i]);
            //                    count = count + 1;
            //                }
                        
            //            }
            //            if (count == 0) {
            //                $rootScope.showAlert($filter('translate')('B1203.msg.labelno_select'));
            //            } else if (count > 1) {
            //                $rootScope.showAlert($filter('translate')('B1203.msg.labelno_select'));
            //            }
            //            dialog.hide();
            //        }
            //    }
            //    return controller;
            //}

            // 输入打印份数
            $scope.input_print_qty = function (event, Copies) {
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                $calculater.open(function (num, dialogNum) {
                    if (num == 0) {
                        $rootScope.showAlert($filter('translate')('B1201.msg.column02'));
                        return;
                    }
                    angular.element(target).removeClass('is-focus');
                    $scope.Copies = num;
                    dialogNum.hide();
                },
                function (dialogNum) {
                    angular.element(target).removeClass('is-focus');
                    dialogNum.hide();
                },
                {
                    defaultNum: $scope.Copies,
                    decimal: false
                });
            };

            // 送出打印
            $scope.print = function () {
                if ($scope.warehouseInfo.labelno == '') {
                    $scope.$root.showAlert($filter('translate')('B1203.msg.please_select_labelno'));

                } else {
                    //for (var i = 0; i < $scope.selectedList.length; i++) {
                    //    remainingPrintDataProcess($scope.selectedList[i]);

                    //}


                        remainingPrintDataProcess();

                   
                }
                                          
            };

            // 打印服務
            var pdf_url;
            function remainingPrintDataProcess(storage_plot) {
               
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.remaining_print_process',
                    content: {
                        print_data: $scope.selectedList,
                        storage_plot: storage_plot || '',
                        CopyMode: '1',
                        labelno: $scope.warehouseInfo.labelno,
                        Copies: $scope.Copies
                    },
                    success: function (data) {

                        if (data.runcard_pdf_get.length == 0 && data.command_lines.length == 0) {
                            $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                        }
                        else {
                            // 執行標籤列印 
                            if (data.command_lines && data.command_lines.length > 0) {
                                printTag(data.command_lines, 0, data.runcard_pdf_get);
                            }
                            // 執行 PDF列印
                            if (data.runcard_pdf_get && data.runcard_pdf_get.length > 0) {
                                 
                                for(var i = 0; i < data.runcard_pdf_get.length; i++){
                                    pdf_url = data.runcard_pdf_get[i].url_pdf;
                                    if(pdf_url.indexOf('http://') == -1){
                                        pdf_url = 'http://'+config.server.ip+':'+config.server.port+ pdf_url;
                                    }
                                    print(pdf_url, data.runcard_pdf_get[i].printCount);
                                }

                                //// sMES內建列印功能只有 Windows用戶可以使用
                                //if (window.nodeRequire) {
                                //    // 規格需要不跳 iframe，並直接列印，但只有 Windows用戶可以
                                //    printDirectly(pdf_url);
                                //} else {
                                //    // 所以不是 Windows用戶的話，就需要跳 iframe，並使用電腦內建列印功能
                                //    showPDFViewer(pdf_url);
                                //}
                            }
                            $scope.selectedList = [];
                            $scope.warehouseInfo.labelno = '';
                        }
                    }
                });
            };


            // 批量打印
            function printBatch(runcard_pdf_get, index) {
                if (index < runcard_pdf_get.length) {
                    pdf_url = runcard_pdf_get[index].url_pdf;
                    if (pdf_url.indexOf('http://') == -1) {
                        pdf_url = 'http://' + config.server.ip + ':' + config.server.port + pdf_url;
                    }
                    print(pdf_url, function callback() {
                        index = index + 1;
                        printBatch(runcard_pdf_get, index);
                    });

                }
            };




            // 條碼列印
            var isError = false;
            function printTag(commandLines, index, runcard_pdf_get) {
                if (commandLines && index < commandLines.length) {
                    if (window.nodeRequire) {
                        var exec = window.nodeRequire('child_process').exec;
                        exec(commandLines[index], function (error, stdout, stderr) {
                            if (error) {
                                isError = true;
                                $rootScope.showAlert($filter('translate')('B1201.msg.cantprint'));
                            }
                            index = index + 1;
                            printTag(commandLines, index, runcard_pdf_get);
                        });
                    }
                } else {
                    if (!isError) {
                        isError = false;
                        $scope.$root.showToast($filter('translate')('common.msg.success'));
                        if (runcard_pdf_get && runcard_pdf_get.length === 0) {
                            printWiplogProcess(1);
                        }
                    }
                }
            };


            // PDF列印
            function print(pdf_url, printCount) {
                // 20201110 modify by WeiTing for M#80602 - 增加多張列印功能(printCount)。
                for (var i = 0; i < printCount; i++) {
                    if (window.nodeRequire) {
                        var sumatraPDF = window.nodeRequire('sumatra-pdf');
                        if (sumatraPDF) {
                            var fs = window.nodeRequire('fs'), RuncardPath;
                            try {
                                // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                                const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                                RuncardPath = remote.app.getAppPath();
                            } catch (e) {
                                RuncardPath = window.nodeRequire('path').dirname(process.execPath) + '\\package.nw';
                            }
                            RuncardPath += '\\www\\Runcard';
                            if (!fs.existsSync(RuncardPath)) {
                                fs.mkdirSync(RuncardPath);
                            }

                            // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                            // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                            fs.readdirSync(RuncardPath, (err, files) => {
                                if (err) {
                                    console.log(err);
                                }
                                //listing all files using forEach
                                files.forEach((file) => {
                                    // Do whatever you want to do with the file
                                    fs.unlink(RuncardPath + '/' + file, (err) => {
                                        if (err) {
                                            console.debug(err);
                                        }
                                    })
                                });
                            })
        
                            // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                            let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                            $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                                $rootScope.showLoading();
                                // 20201110 modify by WeiTing for M#80602 - 不跳列印介面，直接使用預設列印機進行列印(printToDefault)。
                                var _fn = sumatraPDF.printToDefault;
                                _fn({
                                    path: dist_path,
                                    success: function () {
                                        $rootScope.hideLoading();
                                        $rootScope.showToast($filter('translate')('common.msg.success'));
                                    },
                                    error: function (error) {
                                        $rootScope.hideLoading();
                                        $rootScope.showToast($filter('translate')('common.msg.success'));
                                        //console.error(error);
                                    }
                                });
                            });
                        } else {
                            window.frames['kmi-pdf-panel'].pdf_print();
                        }
                    } else {
                        window.frames['kmi-pdf-panel'].pdf_print();
                    }
                }
            };


            // 直接打印
            function printDirectly(pdf_url) {
                var sumatraPDF = window.nodeRequire('sumatra-pdf');
                if (sumatraPDF) {
                    var fs = window.nodeRequire('fs'), RuncardPath;
                    try {
                        RuncardPath = window.nodeRequire('electron').remote.app.getAppPath();
                    } catch (e) {
                        RuncardPath = window.nodeRequire('path').dirname(process.execPath) + '\\package.nw';
                    }
                    RuncardPath += '\\www\\Runcard';
                    if (!fs.existsSync(RuncardPath)) {
                        fs.mkdirSync(RuncardPath);
                    }

                    // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                    // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                    fs.readdirSync(RuncardPath, (err, files) => {
                        if (err) {
                            console.log(err);
                        }
                        //listing all files using forEach
                        files.forEach((file) => {
                            // Do whatever you want to do with the file
                            fs.unlink(RuncardPath + '/' + file, (err) => {
                                if (err) {
                                    console.debug(err);
                                }
                            })
                        });
                    })

                    // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                    let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                    $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                        $scope.$root.showLoading();
                        window.nodeRequire('sumatra-pdf').printWithSettings({
                            path: dist_path,
                            success: function () {
                                printWiplogProcess(1); // 列印完成後，需把列印詳情回送給後台做記錄
                                $scope.$root.hideLoading();
                                $scope.$root.showToast($filter('translate')('common.msg.success'));
                            },
                            error: function (error) {
                                // 20201104 modify by WeiTing for M#77013 - 不清楚為何列印後，實際列印一張紙和輸入成 PDF檔案都會執行 error 區域，所以目前也先列印完成後，把列印詳情回送給後台做記錄。
                                printWiplogProcess(1); // 列印完成後，需把列印詳情回送給後台做記錄
                                $scope.$root.hideLoading();
                                $scope.$root.showToast($filter('translate')('common.msg.success'));
                                //console.error(error);
                            }
                        });
                    });
                } else {
                    // 列印出狀況就跳 iframe，並使用電腦內建列印功能
                    showPDFViewer(pdf_url);
                }
            }

            function showPDFViewer(pdf_url) {
                try {
                    window.nodeRequire('nw.gui').Window.open(pdf_url, {
                        title: 'PDF Viewer',
                        show: false,
                        icon: 'icon/icon.png',
                        focus: true
                    }, function (win) {
                        win.on('loaded', function () {
                            win.show();
                            win.print();
                        });
                    });
                } catch (e) {
                    $scope.mode = 'print';
                    document.getElementById('kmi-pdf-panel').src = 'JSplugins/pdfjs/web/viewer.html?file=' + pdf_url + '&openfile=false&viewbookmark=false&printfile=false&download=false#zoom=page-width';
                }
            }
            

        }
    ];
});
